## Create Figure A1

## Loading packages
library(tidyverse)
library(sf)
library(foreign)
library(readxl)

## Load school boundaries
es1314 = st_read("attende1314.shp")

## Load list of LAUSD schools -- keep just district 4
schools = read_excel("school_ids.xlsx") %>%
  mutate(district = str_trim(district),
         district = as.numeric(district)) %>%
  filter(district %in% c(4))

## Load school identifiers
es1314_keys = read.dbf("attende1314_codes.dbf") %>%
  select(SCHOOL_ID, NAME, KEY_) %>%
  filter(SCHOOL_ID %in% schools$school_id) ## Keep just schools in 4

## Aggregate boundaries to the school-levels
## Some schools are split into separate geographic boundaries
es1314 = es1314 %>%
  left_join(., es1314_keys, by = "KEY_") %>%
  filter(!is.na(SCHOOL_ID)) %>% ## Drop if not in district 4
  group_by(SCHOOL_ID, NAME) %>% 
  summarise(geometry = st_union(geometry)) %>%
  mutate(SCHOOL_ID = as.numeric(as.character(SCHOOL_ID)))

## Load 2013 election precict boundaries
precincts13 = st_read("LACity.shp")

## Create district-precinct crosswalk
districts13 = read_excel("primary.xlsx") %>%
  filter(year == 2013) %>%
  select(precinct, district)

precincts13 = precincts13 %>%
  left_join(., districts13, by = c("CNSLD" = "precinct")) %>%
  filter(!is.na(district)) ## Keeping only districts with elections in 2013

xwalk_es1314 = st_intersection(es1314, precincts13) %>%
  select(SCHOOL_ID, NAME, geometry, district, CNSLD) %>%
  filter(district == 4)

xwalk_es1314$area = unclass(st_area(xwalk_es1314$geometry))


## Plot map
needed = xwalk_es1314 %>%
  filter(SCHOOL_ID == 6110 | SCHOOL_ID == 2306)

## Create combination of 9000552A
combo = needed %>%
  filter(CNSLD == "9000552A") %>%
  summarise(geometry = st_union(geometry))

figureA1 = ggplot(data = needed) +
  geom_sf(aes(fill = factor(SCHOOL_ID)), 
          size = 0) +
  geom_sf(
    data = combo,
    
    fill=NA, colour="red4",
    size=1,
    inherit.aes=FALSE) +
  
  geom_sf(
    data = . %>% filter(CNSLD == "1060001A"),
    
    fill=NA, colour="blue4",
    size=1,
    inherit.aes=FALSE) +
  scale_fill_manual(name = "School", values = c("gray75", "gray45"),
                    labels = c("Playa Vista ES", "Playa Del Rey ES")) +
  coord_sf(datum = NA) +
  theme_classic() +
  theme(legend.position="right",
        #plot.margin=grid::unit(c(0,0,0,0), "mm"),
        legend.margin = margin(t = 0, r = 35, b = -185, l = -150, unit = "pt"))
